package oj;
import java.util.*;

public class Solution_145 {
    //这种方法被调用多次，ans 对象就会被创建多次
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        if(root == null){
            return ans;
        }
        ans.addAll(postorderTraversal(root.left));
        ans.addAll(postorderTraversal(root.right));
        ans.add(root.val);

        return ans;
    }
    //进行改进：这样只会有一个对象存在
    public static void postorInternal(TreeNode root, List<Integer> ans){
        if(root == null){
            return ;
        }
        postorInternal(root.left,ans);
        postorInternal(root.right,ans);
        ans.add(root.val);

    }
    public static List<Integer> postorTraversal1(TreeNode root){
        List<Integer> ans = new ArrayList<>();
        postorInternal(root,ans);
        return ans;
    }

    public static void main(String[] args) {
        TreeNode n1 = new TreeNode(1);
        TreeNode n2 = new TreeNode(2);
        TreeNode n3 = new TreeNode(3);
        TreeNode n4 = new TreeNode(4);
        TreeNode n5 = new TreeNode(5);
        TreeNode n6 = new TreeNode(6);
        TreeNode n7 = new TreeNode(7);
        TreeNode n8 = new TreeNode(8);
        TreeNode n9 = new TreeNode(9);
        TreeNode n10 = new TreeNode(10);
        TreeNode n11 = new TreeNode(11);

        n1.left = n2;   n1.right = n3;
        n2.left = n4;   n2.right = n5;
        n3.left = null; n3.right = n6;
        n4.left = null; n4.right = null;
        n5.left = n7;   n5.right = n8;
        n6.left = n9;   n6.right = null;
        n9.left = n10;  n9.right = n11;
        Solution_145 solution_145 = new Solution_145();
        List<Integer> list = solution_145.postorTraversal1(n1);
        System.out.println(list);
    }
}
